import React from 'react';
import { HashRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import App from '../App';
import Admin from '../admin';
import Login from '../pages/login';
import Nomatch from '../pages/nomatch';
import MenuConfig from "./routerConfig";


export default class ERouter extends React.Component {
    state = {
        currentKey: ''
    }

    componentWillMount() {
        let currentKey = window.location.hash.replace(/#|\?.*$/g, '');
        this.setState({
            currentKey
        })
        // this.props.history.push('/home');
    }
    /*是否需要重定向*/
    isRedirectPath = (routes, pathname) => routes.find(route => {
        if (route.children) {
            this.isRedirectPath(route.children, pathname);
        }
        // if (route.path === pathname && route.redirect && route.redirect !== route.path) {
        //     // this.props.history.push(route.redirect)
        //     this.props.history.push(route.redirect);
        // }
        return route.path === pathname && route.redirect && route.redirect !== route.path
    })
    // 路由渲染
    RouteComponent = (route) => {
        return <Route key={route.path} exact={route.exact ? route.exact : false} path={route.path} component={route.component} />
    }
    // 路由表渲染
    renderRouteComponent = routes => routes.map((route, index) => {
        if (route.children) {
            return this.renderRouteComponent(route.children);
        }
        return this.RouteComponent(route);
    })

    render() {
        let isRedirectPath = this.isRedirectPath(MenuConfig, this.state.currentKey);

        return (
            <Router>
                <App>
                    <Switch>
                        <Route path="/login" component={Login} />
                        <Route path="/" render={() =>
                            <Admin>
                                <Switch>
                                    {
                                        this.renderRouteComponent(MenuConfig)
                                    }
                                    {/*<Redirect to="/home"/>*/}
                                    <Route component={Nomatch} />
                                </Switch>
                            </Admin>
                        } />
                    </Switch>
                </App>
            </Router>
        )
    }
}